package com.study.hot.jetpack.room.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.study.hot.jetpack.room.one2many.IdCard
import com.study.hot.jetpack.room.one2many.IdCardDao
import com.study.hot.jetpack.room.one2many.Person
import com.study.hot.jetpack.room.one2many.PersonDao

/**
 * <pre>
 *     author : slx
 *     time   : 2021/02/25
 *     desc   :
 * </pre>
 */
@Database(entities = [User::class, Person::class, IdCard::class], version = 1/*数据库升级测试为2*/, exportSchema = false)
abstract class AppDataBase : RoomDatabase() {
    abstract fun getUserDao(): UserDao

    abstract fun getPersonDao(): PersonDao
    abstract fun getIdCardDao(): IdCardDao

    // 单例获取DataBase
    companion object {

        // 版本升级管理
        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE t_user ADD COLUMN des TEXT")
            }
        }

        private var instance: AppDataBase? = null
        fun getInstance(context: Context): AppDataBase {
            if (instance == null) {
                instance = Room.databaseBuilder(
                        context.applicationContext,
                        AppDataBase::class.java, "app_db"
                ).allowMainThreadQueries()
                        /*.addMigrations(MIGRATION_1_2)*/.build()

            }
            return instance as AppDataBase
        }
    }
}